package com.joshua.spring.aspect;

import com.joshua.spring.entity.em.ResponseEnum;
import com.joshua.spring.entity.vo.GlobalResponse;
import com.joshua.spring.exception.InnerServiceException;
import com.joshua.spring.exception.MicroServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * com.joshua.spring.common.aspect -- LocalExceptionHandler
 * description: 全局异常处理
 *
 * @author joshua_liu <a href="mailto:joshualwork@163.com"/>
 * On 2019/12/11 18:06
 */
@Slf4j
@RestControllerAdvice
public class MicroServiceExceptionHandler {
    @ExceptionHandler(value = MicroServiceException.class)
    public ResponseEntity<GlobalResponse> baseErrorHandler(MicroServiceException e) {
        log.error("Catch global micro service exception:", e);
        return responseEntityBuilder(e.getGlobalResponse());
    }

    @ExceptionHandler(value = InnerServiceException.class)
    public ResponseEntity<GlobalResponse> innerErrorHandler(InnerServiceException e) {
        log.error("Catch global inner service exception:", e);
        return responseEntityBuilder(e.getGlobalResponse());
    }

    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ResponseEntity<GlobalResponse> noHandlerFoundHandler(NoHandlerFoundException e) {
        log.error("Catch resource not found exception:", e);
        return responseEntityBuilder(GlobalResponse.buildFail(ResponseEnum.NOT_FOUND));
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<GlobalResponse> unknownErrorHandler(Exception e) {
        log.error("Catch global unknown exception:", e);
        return responseEntityBuilder(GlobalResponse.buildFail(e.getMessage()));
    }

    private ResponseEntity<GlobalResponse> responseEntityBuilder(GlobalResponse globalResponse) {
        return ResponseEntity.status(HttpStatus.valueOf(globalResponse.getStatus())).body(globalResponse);
    }
}
